<template>
  <el-form ref="userInfoForm" :model="userBasicInfo" :rules="userInfoRules" label-width="120px" class="demo-ruleForm"
    size="default" status-icon>
    <p class="subCardTitle">基本信息</p>
    <div class="card_avatar">
      <img :src="avatar" class="avatar" title="IWu" />
      <el-upload class="upload-demo" ref="uploadRef" v-model:file-list="fileList" action="/api/auth/upAvatar"
        :data="data()" :headers="headers" :on-success="handSuccess" :on-exceed="handExceed"
        :before-upload="beforeAvatarUpload" list-type="picture" :auto-upload="false" :limit="1">
        <template #trigger>
          <el-button type="primary" class="upstateAvatar">修改头像</el-button>
        </template>
      </el-upload>
    </div>
    <el-form-item label="姓名" prop="name" style="margin-top: 10px;">
      <el-input v-model="userBasicInfo.name" style="width: 100px;" />
    </el-form-item>
    <el-form-item label="性别" prop="gander">
      <el-radio-group v-model="userBasicInfo.gander">
        <el-radio label="男" />
        <el-radio label="女" />
      </el-radio-group>
    </el-form-item>
    <el-form-item label="出生年月" style="width: 500px;" required>
      <el-col :span="11">
        <el-form-item prop="birth">
          <el-date-picker v-model="userBasicInfo.birth" type="date" value-format="YYYY-MM" format="YYYY-MM" label="请选择时间"
            placeholder="请选择时间" style="width: 100%" />
        </el-form-item>
      </el-col>
    </el-form-item>
    <el-form-item label="政治面貌" style="width: 295px;" prop="politicalOutlook">
      <el-select v-model="userBasicInfo.politicalOutlook" placeholder="请选择">
        <el-option label="党员" value="党员" />
        <el-option label="团员" value="团员" />
      </el-select>
    </el-form-item>
    <el-form-item label="户籍地" prop="birthAddress">
      <el-cascader style="width: 200px;" :options="options" v-model="userBasicInfo.birthAddress" separator="-"
        placeholder="请选择">
      </el-cascader>
    </el-form-item>
    <el-form-item label="现居城市" prop="newAddress">
      <el-cascader style="width: 200px;" :options="options" v-model="userBasicInfo.newAddress" separator="-"
        placeholder="请选择">
      </el-cascader>
    </el-form-item>
    <el-form-item label="电话" prop="">
      <el-input v-model="userBasicInfo.phone" style="width: 200px;" readonly />
    </el-form-item>
    <el-form-item label="邮箱" prop="">
      <el-input v-model="userBasicInfo.email" style="width: 200px;" readonly />
    </el-form-item>
    <el-form-item>
      <el-button type="success" @click="saveInfo(userInfoForm)">保存</el-button>
      <el-button @click="cancelEdit(userInfoForm)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>

import { defineComponent, reactive, ref, computed, onMounted, getCurrentInstance } from 'vue'
import { getAddressCode, getAddressText, elmessage, data } from "@/hook/hook"
import type { FormInstance, FormRules } from 'element-plus'
import { userBasicInfo, userInfoRules } from "@/utills/userInfoValidators"

import { useStore } from "vuex"
import { provinceAndCityData } from 'element-china-area-data'
import { UploadProps, UploadUserFile, UploadInstance, genFileId, UploadRawFile, ElMessage } from 'element-plus'

import { useRouter } from "vue-router"
const router = useRouter()
const store = useStore()

const userInfoForm = ref<FormInstance>()
const options = provinceAndCityData
const avatar = ref()
// @ts-ignore
const { proxy } = getCurrentInstance() // 1.获取proxy实例

// 用户头像上传
const uploadRef = ref<UploadInstance>()
const headers = reactive({
  Authorization: localStorage.getItem("loginData") ? JSON.parse(localStorage.getItem("loginData") || "").token : null,
})


const fileList = ref<UploadUserFile[]>([])


const handExceed: UploadProps['onExceed'] = (files) => {
  uploadRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadRef.value!.handleStart(file)
}
const handSuccess: UploadProps['onSuccess'] = (response: any, UploadFile: any, UploadFiles: any) => {
  // 上传成功后将头像更换
  // console.log(UploadFile.raw);
  store.state.userState.userBasicInfo.avatar = window.URL.createObjectURL(UploadFile.raw)
  fileList.value = []

}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }


  return true
}


onMounted(() => {
  
  
  userBasicInfo.name = store.state.userState.userBasicInfo.name
  userBasicInfo.gander = store.state.userState.userBasicInfo.gander
  userBasicInfo.birth = store.state.userState.userBasicInfo.birth
  userBasicInfo.birthAddress = getAddressCode(store.state.userState.userBasicInfo.birthAddress)
  userBasicInfo.newAddress = getAddressCode(store.state.userState.userBasicInfo.newAddress)

  userBasicInfo.politicalOutlook = store.state.userState.userBasicInfo.politicalOutlook
  userBasicInfo.phone = store.state.userState.userBasicInfo.phone
  userBasicInfo.email = store.state.userState.userBasicInfo.email
  avatar.value = store.state.userState.userBasicInfo.avatar
  
})

// 记：按当前本人的学识只能将头像和数据分开上传
// 即头像和数据修改都需要各自发一次请求
// 头像若是未修改则不会发送请求，这是我疑惑的地方

// const userInfoForm = ref<FormInstance>()
// 提交按钮
const saveInfo = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 将图片上传到数据库
      if (uploadRef.value != null) {
        uploadRef.value!.submit()
      }

      // console.log(uploadRef.value)
      userBasicInfo.birthAddress = getAddressText(userBasicInfo.birthAddress)
      userBasicInfo.newAddress = getAddressText(userBasicInfo.newAddress)
      // 提交信息
      store.commit("upUserBasicInfo", userBasicInfo)
      // 关闭编辑页
      store.commit("editBasicUserInfo")
      // 将信息提交给后端,不包括图片
      // console.log(data(),"sasaa");

      const updata = { ...data(), ...userBasicInfo, ...{ upPart: "basicInfo" } }
      // console.log(updata,"asdsadad");

      proxy.$api.userApi.upUserInfo(updata).then((res: any) => {
        if (res.data["code"] = "200") {
          elmessage(res.data.message, res.data.type)
        } else if (res.data["code"] == "300") {
          elmessage(res.data["message"], res.data["type"])
          setTimeout(() => {
            router.replace("/login")
          }, 500);
          localStorage.clear()
        } else {
          console.log(res.data);

        }


      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 取消按钮
function cancelEdit(formEl: FormInstance | undefined) {
  if (!formEl) return
  userBasicInfo.birthAddress = getAddressText(userBasicInfo.birthAddress)
  userBasicInfo.newAddress = getAddressText(userBasicInfo.newAddress)
  formEl.resetFields()
  store.commit("editBasicUserInfo")

}
</script>
<style scoped>
.upload-demo {
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
}

.card_avatar {
  position: absolute;
  margin-left: 700px;
  margin-top: 20px;
  width: 150px;
  height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
}

.avatar {
  margin-bottom: 10px;
  height: 110px;
  width: 110px;
  border-radius: 100%;

}

.subCardTitle {
  padding-left: 30px;
  padding-top: 10px;
  padding-bottom: 10px;
  font-size: 18px;
  width: calc(100%-30px);
  /* height: 25px; */
  background-color: rgb(234, 242, 253);
}

.demo-ruleForm {
  height: 500px;
}

.demo-ruleForm:hover {
  transition-duration: 0.3s;
  transition-property: box-shadow;
  box-shadow: 0 0 3px #97999b;
  cursor: pointer;
}
</style>
